import { FC, useEffect, useState } from "react";
import styles from "./QuestionCheckbox.module.scss";

type PropsType = {
  fe_id: string;
  props: {
    title: string;
    isVertical?: boolean;
    list: Array<{
      value: string;
      label: string;
      checked: boolean;
    }>;
  };
};

const QuestionCheckbox: FC<PropsType> = ({ fe_id, props }) => {
  const { title, isVertical, list = [] } = props;

  const [selectedValues, setSelectedValues] = useState<string[]>([]);

  // 初始化时，判断默认选中
  useEffect(() => {
    let selectVals: string[] = [];
    list.forEach((item) => {
      if (item.checked) {
        selectVals.push(item.value);
      }
    });
    setSelectedValues(selectedValues.concat(selectVals));
  }, [list]);

  const toggleChecked = (value: string) => {
    if (selectedValues.includes(value)) {
      setSelectedValues(selectedValues.filter((s) => s !== value));
    } else {
      setSelectedValues(selectedValues.concat(value));
    }
  };

  return (
    <>
      <p>{title}</p>
      <input type="hidden" name={fe_id} value={selectedValues.toString()} />
      <ul className={styles.list}>
        {list.map((item) => {
          const { label, value } = item;

          let className;
          if (isVertical) className = styles.verticalItem;
          else className = styles.horizontalItem;

          return (
            <li key={value} className={className}>
              <label>
                <input
                  type="checkbox"
                  checked={selectedValues.includes(value)}
                  onChange={() => toggleChecked(value)}
                />
                {label}
              </label>
            </li>
          );
        })}
      </ul>
    </>
  );
};

export default QuestionCheckbox;
